package com.aternity.vbd.ui;

import org.apache.commons.lang.StringUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

/**
 * @author Daniel Orr
 */
public class HourPicker extends JTextField implements KeyListener {

    public HourPicker() {
        super("00:00");
        this.addKeyListener(this);
    }

    public long getTimeMillis(){
        return getHourPart()*60*60*1000 + getMinutesPart()*60*1000;
    }

    public int getHourPart() {
        final String[] splits = StringUtils.split(getText(), ':');
        return Integer.parseInt(splits[0]);
    }

    public int getMinutesPart() {
        final String[] splits = StringUtils.split(getText(), ':');
        return Integer.parseInt(splits[1]);
    }

    public void setHourPart(int hour) {
        if (hour > 23 || hour < 0)
            return;
        final int minutes = getMinutesPart();
        setText(paddedStr(hour) + ":" + paddedStr(minutes));
    }

    private String paddedStr(int hour) {
        String h = Integer.toString(hour);
        h = h.length() == 1 ? "0" + h : h;
        return h;
    }

    public void setMinutesPart(int minutes) {
        if (minutes > 59 || minutes < 0)
            return;
        final int hour = getHourPart();
        setText(paddedStr(hour) + ":" + paddedStr(minutes));
    }

    public int getTotalMinutes() {
        return getHourPart() * 60 + getMinutesPart();
    }

    @Override
    public void keyTyped(KeyEvent e) {
        e.consume();
    }

    @Override
    public void keyPressed(KeyEvent e) {
        final int caretPosition = getCaretPosition();
        final int keyCode = e.getKeyCode();
        if (keyCode == 38) {
            if (caretPosition <= 2) {
                setHourPart(getHourPart() + 1);
            } else {
                setMinutesPart(getMinutesPart() + 1);
            }
        }
        if (keyCode == 40) {
            if (caretPosition <= 2) {
                setHourPart(getHourPart() - 1);
            } else {
                setMinutesPart(getMinutesPart() - 1);
            }
        }
        setCaretPosition(caretPosition);
    }

    @Override
    public void keyReleased(KeyEvent e) {

    }

    public static void main(String[] args) {
        JFrame jf = new JFrame();
        jf.setLayout(new FlowLayout());
        jf.setSize(300, 300);
        jf.add(new HourPicker());
        jf.setVisible(true);
    }
}
